package com.hll.basic;

import com.hll.basic.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author hll
 * @create 2022-05-12 16:00
 */
@Controller
@RequestMapping("/param") // 前缀
public class ParameterController {
  @RequestMapping("/servlet")
  // 形参位置的request表示当前请求
  public String testServletAPI(HttpServletRequest request) {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println("username:" + username + ",password:" + password);
    return "success";
  }

  @RequestMapping("/anno")
  public String testParam(
      @RequestParam(value = "user_name", required = false, defaultValue = "nick") String username,
      String password,
      String[] hobby,
      @RequestHeader(value = "Host", required = false, defaultValue = "127.0.0.1") String host,
      @CookieValue("JSESSIONID") String JSESSIONID) {
    // 若请求参数中出现多个同名的请求参数，可以再控制器方法的形参位置设置字符串类型或字符串数组接收此请求参数
    // 若使用字符串类型的形参，最终结果为请求参数的每一个值之间使用逗号进行拼接
    /*
    username:admin,password:111,hobby:[a, b]
    host:localhost:8080
    JSESSIONID:1222A3644B56B30E2A98EDF71C24D3D8
         */
    // @RequestHeader可以拿到header信息，像之前的token的Authentication就可以这么拿
    System.out.println(
        "username:" + username + ",password:" + password + ",hobby:" + Arrays.toString(hobby));
    System.out.println("host:" + host);
    System.out.println("JSESSIONID:" + JSESSIONID);
    return "success";
  }

  /*可以不给全属性（一个不给都行），默认为null，确保字段名与属性名一致*/
  @RequestMapping("/bean")
  public String testBean(User user) {
    System.out.println(user);
    return "success";
  }
}
